package com.gitee.wsl.ext.string

import com.gitee.wsl.ext.base.CR
import com.gitee.wsl.ext.base.LF

/**
 * If this string ends with comma(,) - will return the string with trailing comma removed.
 * Otherwise, returns this string.
 *
 * @return string with the result
 */
fun String.removeTrailingComma(): String = this.removeSuffix(",")


/**
 * Removes non-numerical characters from a string.
 */
fun String.removeNonAlpha() =
    replace("[^a-zA-Z\\s]".toRegex(), " ").replace(" +".toRegex(), " ").trim()

//fun String.removeAll(c:Char) :String{
//    if(isBlank()) return this
//    val builder = StringBuilder()
//    forEach { if( c != it ) builder.append(it) }
//    return builder.toString()
//}

fun String.removeAll(vararg cs:Char) :String{
    if(isBlank()) return this
    val builder = StringBuilder()
    forEach { if( !cs.contains(it) ) builder.append(it) }
    return builder.toString()
}

/**
 * 去除所有换行符，包括：
 *
 * <pre>
 * 1. \r
 * 1. \n
</pre> *
 *
 * @return 处理后的字符串
 * @since 4.2.2
 */
fun String.removeAllLineBreaks(): String {
    return removeAll( Char.CR, Char.LF)
}

/**
 * 去掉首部指定长度的字符串并将剩余字符串首字母小写<br></br>
 * 例如：str=setName, preLength=3 =》 return name
 *
 * @param str       被处理的字符串
 * @param preLength 去掉的长度
 * @return 处理后的字符串，不符合规范返回null
 */
fun String.removePreAndLowerFirst(preLength: Int): String {
    val str = this
    if (str.length > preLength) {
        val first = str[preLength].lowercaseChar()
        if (str.length > preLength + 1) {
            return first.toString() + str.substring(preLength + 1)
        }
        return first.toString()
    } else {
        return str
    }
}
